//
//  ViewController.swift
//  5.3.Animating Your UI Components with a Push
//
//  Created by joker on 15/7/31.
//  Copyright (c) 2015年 joker. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    var squareView: UIView?
    var animator: UIDynamicAnimator?
    var pushBehavior: UIPushBehavior?
    
    func createSmallSquareView() {
        squareView = UIView(frame: CGRect(x: 0, y: 0, width: 80, height: 80))
        if let theSquareView = squareView {
            theSquareView.backgroundColor = UIColor.greenColor()
            theSquareView.center = view.center
            view.addSubview(theSquareView)
        }
    }
    
    func createGestureRecognizer(){
        let tapGestureRecoginzer = UITapGestureRecognizer(target: self, action: "handleTap:")
        view.addGestureRecognizer(tapGestureRecoginzer)
    }
    
    func handleTap(tap:UITapGestureRecognizer) {
        let tapPoint = tap.locationInView(view)
        let squareViewCenterPoint = self.squareView!.center
        
        let deltaX = tapPoint.x - squareViewCenterPoint.x
        let deltaY = tapPoint.y - squareViewCenterPoint.y
        let angle = atan2(deltaY,deltaX)
        
        pushBehavior!.angle = angle
        
        let distanceBetweenPoints = sqrt(pow(tapPoint.x - squareViewCenterPoint.x, 2.0) + (pow(tapPoint.y - squareViewCenterPoint.y,2.0)))
        
        pushBehavior!.magnitude = distanceBetweenPoints / 200.0
    }
    
    func createAnimatorAndBehaviors() {
        animator = UIDynamicAnimator(referenceView: view)
        if let theSquareView = squareView {
            let collision = UICollisionBehavior(items: [theSquareView])
            collision.translatesReferenceBoundsIntoBoundary = true
            pushBehavior = UIPushBehavior(items: [theSquareView], mode: .Continuous)
            
            animator!.addBehavior(collision)
            animator!.addBehavior(pushBehavior)
        }
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        createGestureRecognizer()
        createSmallSquareView()
        createAnimatorAndBehaviors()
    }
}

